import QtQuick 1.1
import com.nokia.meego 1.0
import "Logic.js" as Logic

Page {
    id: pageCategoryList

    property string selCategoryId: ""
    property string selCategoryName: ""
    property string selCategoryDescr: ""
    property bool isEditCategory: false

    tools: ToolBarLayout {
        id: tool_only_back
        opacity: userTheme.opacityToolbar
        ToolIcon {
            id: toolIconBack
            //iconId: "toolbar-back"
            iconSource: "images/toolbar/back.png"
            onClicked: {
                pageStack.pop();
            }
        }
        ToolIcon {
            id: toolIconRemove
            //iconId: "toolbar-delete"
            iconSource: "images/toolbar/close.png"
            onClicked: {
                if( selCategoryId != "" ) {
                    dlgRemoveCategory.open()
                }
            }
        }
        ToolIcon {
            id: toolIconEdit
            //iconId: "toolbar-edit"
            iconSource: "images/toolbar/edit.png"
            onClicked: {
                isEditCategory = true
                Logic.openFile("AddCategory.qml")
            }
        }
        ToolIcon {
            id: toolIconAdd
            //iconId: "toolbar-add"
            iconSource: "images/toolbar/add.png"
            onClicked: {
                isEditCategory = false
                Logic.openFile("AddCategory.qml")
            }
        }
    } //ToolBarLayout

    QNMTitle {
        id: titlePage
        text: qsTr("List of categories")
        image: "images/categories.png"
        busy: false
    }

    BackgroundPage { }

    function getAllCategory() {
        titlePage.busy = true
        //console.log("getAllCategory()")
        var db = Logic.getDatabase()

        listModelCategory.clear()

        db.transaction( function(tx) {
                           var res = tx.executeSql ( ""+
                                                   "SELECT c.category, c.description, c.id, count(w.category_id) AS cnt FROM categories c " +
                                                   "LEFT JOIN words w ON c.id = w.category_id " +
                                                   "GROUP BY c.id" +
                                                   "" )

                           for(var i = 0; i<=res.rows.length-1; i++) {
                               if(i == 0) {
                                   selCategoryId = res.rows.item(i).id;
                                   selCategoryName = res.rows.item(i).category;
                                   selCategoryDescr = res.rows.item(i).description;
                               }
                               var id = res.rows.item(i).id;
                               var nameCategory = res.rows.item(i).category;
                               var descrCategory = res.rows.item(i).description;
                               var numw = res.rows.item(i).cnt;
                               listModelCategory.append( {category_id: id, name: nameCategory, descr: descrCategory, words: numw } );
                           }
                       }
                    )
        /* установка значение для первого элемента */
        titlePage.busy = false
    }

    function removeCategory( id ) {
        var db = Logic.getDatabase()

        /* удаление слов из категории */
        db.transaction( function(tx) {
                           var res = tx.executeSql( "DELETE FROM words WHERE category_id=?",id )
                           //console.log("Delete: "+res)
                       }
                )

        /* удаление категории */
        db.transaction( function(tx) {
                           var res = tx.executeSql( "DELETE FROM categories WHERE id=?",id )
                           //console.log("Delete: "+res)
                       }
                )

        //переинициализация списка кетегорий
        getAllCategory()
    }

    /*------------------------------------------------------*/

    ListModel {
        id: listModelCategory
        Component.onCompleted: getAllCategory()
    }


    ScrollDecorator { flickableItem: listviewCategory }
    ListView {
        id: listviewCategory

        anchors.top: titlePage.bottom
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        anchors.leftMargin: 12
        anchors.rightMargin: 12
        anchors.bottomMargin: 5
        anchors.topMargin: 5

        // Компонент отображения пункта
        Component {
            id: compItemListCategory
            Rectangle {
                id: wrapper
                height: 110
                width: listviewCategory.width
                scale: 0.95
                opacity: 0.6
                border.color: "grey"
                radius: 10
                gradient: Gradient {
                    GradientStop { position: 0; color: "transparent" }
                    GradientStop { position: 1; color: "lightgrey" }
                }
                clip: true
                Image {
                    id: imgItem
                    smooth: true
                    source: "images/categoryItem.png"
                    anchors.verticalCenter: parent.verticalCenter
                    anchors.left: parent.left
                    anchors.leftMargin: 10
                }
                Item {
                    id: itemTextWrapper
                    anchors.verticalCenter: parent.verticalCenter
                    anchors.left: imgItem.right
                    height: parent.height - 10
                    width: parent.width - imgItem.width - 30
                    anchors.leftMargin: 10
                    clip: true
                    Item {
                        id: nameCategory
                        anchors.top: parent.top
                        anchors.topMargin: 5
                        height: parent.height/3
                        width: parent.width
                        clip: true
                        Text {
                            anchors.verticalCenter: parent.verticalCenter
                            text: name
                            font.pixelSize: 30
                            color: userTheme.colorWord
                            font.family: "Nokia Pure Text"
                        }
                    }

                    Item {
                        id: descCategory
                        anchors.top: nameCategory.bottom
                        height: parent.height/3
                        width: parent.width
                        clip: true
                        Text {
                            anchors.verticalCenter: parent.verticalCenter
                            text: Logic.strItemComment( descr )
                            font.pixelSize: 20
                            color: userTheme.colorCategory
                            font.family: "Nokia Pure Text"
                            visible: text == "" ? false : true
                        }
                    }

                    Item {
                        id: wordsCategory
                        anchors.top: descCategory.bottom
                        height: parent.height/3
                        width: parent.width
                        clip: true
                        Text {
                            anchors.verticalCenter: parent.verticalCenter
                            text: qsTr("Words:") + " " + words
                            font.pixelSize: 22
                            color: userTheme.colorTranslation
                            font.family: "Nokia Pure Text"
                        }
                    }
                }

                states: State {
                    name: "Current"
                    when: wrapper.ListView.isCurrentItem
                    PropertyChanges { target: wrapper; scale: 1.0 }
                    PropertyChanges { target: wrapper; opacity: 1.0 }
                }

                transitions: Transition {
                    NumberAnimation { properties: "scale"; duration: 300 }
                    NumberAnimation { properties: "opacity"; duration: 300 }
                }

                MouseArea {
                    id: mouseAreaItem;
                    anchors.fill: parent

                    onClicked: {
                        parent.ListView.view.currentIndex = index
                        selCategoryId = category_id
                        selCategoryName = name
                        selCategoryDescr = descr
                    }

                    onDoubleClicked: {
                        parent.ListView.view.currentIndex = index
                        isEditCategory = true
                        selCategoryId = category_id
                        selCategoryName = name
                        selCategoryDescr = descr
                        Logic.openFile("AddCategory.qml")
                    }
                }
            } // Rectangle
        }

        //компонент подсветки пункта меню
        Component {
            id: sessionItemHighlight
            Rectangle {
                height: 100
                width: listviewCategory.width
                radius: 12
                y: listviewCategory.currentItem.y;
                Behavior on y { SpringAnimation { spring: 5; damping: 0.3 } }
                gradient: Gradient {
                    GradientStop { position: 0; color: "#8997ff" }
                    GradientStop { position: 0.5; color: "lightsteelblue" }
                    GradientStop { position: 1; color: "#8997ff" }
                }
            }
        }


        model: listModelCategory
        delegate: compItemListCategory
        //highlight: sessionItemHighlight
        highlightFollowsCurrentItem: true
        focus: true
        clip: true
    }

    QueryDialog {
        id: dlgRemoveCategory
        icon: "image://theme/icon-m-toolbar-delete-white"
        titleText: qsTr("Deleting category")
        message: qsTr("Delete selected category ?")
        acceptButtonText: qsTr("Yes")
        rejectButtonText: qsTr("No")
        onAccepted: removeCategory( selCategoryId )
    }


}
